package com.riko.comic.core.utils;

import cn.hutool.core.util.IdUtil;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * minio工具类
 *
 * @author riko
 * @since 2021/10/29
 */
@Component
@Slf4j
public class MinioUtil {


    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.url}")
    private String url;

    /**
     * 5MB 分片上传
     */
    private static final Long PART_SIZE = 1024 * 1024L * 5;

    private static final String BUCKET_NAME = "image";


    private MinioClient client;

    private static MinioUtil self;

    public static String uploadFile(MultipartFile file) throws Exception {
        String fileName = IdUtil.simpleUUID();
        PutObjectOptions option = new PutObjectOptions(file.getSize(), PART_SIZE);
        if (!self.client.bucketExists(BUCKET_NAME)) {
            self.client.makeBucket(BUCKET_NAME);
        }
        self.client.putObject(BUCKET_NAME, fileName, file.getInputStream(), option);
        //return self.client.getObjectUrl(BUCKET_NAME,fileName);
        return BUCKET_NAME+"/"+fileName;
    }


    public static String uploadFile(String path) {
        try {
            String fileName = IdUtil.simpleUUID();
            if (!self.client.bucketExists(BUCKET_NAME)) {
                self.client.makeBucket(BUCKET_NAME);
            }

            File file = new File(path);
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
            PutObjectOptions option = new PutObjectOptions(in.available(), PART_SIZE);
            self.client.putObject(BUCKET_NAME, fileName, in, option);
            return self.client.getObjectUrl(BUCKET_NAME,fileName);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("upload file failed...,reason:{}", e.getMessage());
            return null;
        }
    }



    @PostConstruct
    private void init() {
        self = this;
        try {
            client = new MinioClient(url, accessKey, secretKey);
        } catch (InvalidEndpointException e) {
            e.printStackTrace();
        } catch (InvalidPortException e) {
            e.printStackTrace();
        }



    }

}
